package com.zhangxiaofanfan.hotcode.second;

import java.util.Arrays;

/**
 *
 * @date 2024-07-13 03:14:13
 * @author zhangxiaofanfan
 */
public class HotCode085 {
    public static void main(String[] args) {
        HotCode085 hotCode = new HotCode085();
        int[] coins = {1, 2, 5};
        System.out.println(hotCode.coinChange(coins, 11));
    }

    public int coinChange(int[] coins, int amount) {
        if (amount == 0) {
            return 0;
        }
        Arrays.sort(coins);
        if (amount < coins[0]) {
            return -1;
        }
        int[] dp = new int[amount + 1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;
        for (int coinIndex = 0, amountIndex, coinCount, chooseCoinIndex; coinIndex < coins.length; coinIndex++) {
            for (amountIndex = 1; amountIndex <= amount; amountIndex++) {
                coinCount = amountIndex / coins[coinIndex];
                for (chooseCoinIndex = 1; chooseCoinIndex <= coinCount; chooseCoinIndex++) {
                    int balance = amountIndex - coins[coinIndex] * chooseCoinIndex;
                    if (dp[balance] != Integer.MAX_VALUE) {
                        dp[amountIndex] = Math.min(dp[amountIndex], dp[balance] + chooseCoinIndex);
                    }
                }
            }
        }
        return dp[amount] == Integer.MAX_VALUE ? -1 : dp[amount];
    }
}